package com.util;


import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by fei on 2017/6/20.
 */

public class MyThread extends Thread {

    private int flag = 0;
    private Context context;
    private List<String> videourllist = new ArrayList<>();

    public MyThread() {
    }

    public MyThread(int flag, Context context, List<String> videourllist) {
        this.flag = flag;
        this.context = context;
        this.videourllist = videourllist;
    }

    @Override
    public void run() {
        if (2 == flag) { // 复杂文件下载及存储到手机SD卡
            SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo", Context.MODE_MULTI_PROCESS);
            String videoname = sharedPreferences.getString("videoname", "");

            if (videoname == null || videoname.equals("")) {
                videoname = "0";
            }
            int namev = Integer.parseInt(videoname);
            for (int i = 0; i < videourllist.size(); i++) {
                String userInfo = sharedPreferences.getString(videourllist.get(i), "");
                File file = new File("/storage/emulated/0/test_music/", userInfo + ".mp3");
                if (file.exists()) {
                    //路径存在
                    long length = file.length();
                    namev++;
                    new DownUtil2(videourllist.get(i), "v" + namev + ".mp3", length).start();
                    sharedPreferences.edit().putString(videourllist.get(i), "v" + namev).commit();

                } else {
                    //路径不存在
                    namev++;
                    new DownUtil2(videourllist.get(i), "v" + namev + ".mp3", 0).start();
                    sharedPreferences.edit().putString(videourllist.get(i), "v" + namev).commit();
                }
            }
            sharedPreferences.edit().putString("videoname", "" + namev).commit();
        }
    }

    /**
     * 删除单个文件
     *
     * @param filePathName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteSingleFile(String filePathName) {
        File file = new File(filePathName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Log.e("TAG", "删除单个文件成功");
                return true;
            } else {
                Log.e("TAG", "删除单个文件失败");
                return false;
            }
        } else {
            Log.e("TAG", "删除单个文件失败，不存在");
            return false;
        }
    }

}
